<script setup>
import { reactive, ref, getCurrentInstance } from 'vue'
import { onLoad, onReady, onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import List from './components/list.vue'
import NoData from '../../components/no-data/no-data.vue'

import { getPatientList } from '../../services/index/index.js'

let listArray = reactive([])
let isLoadingMore = ref(false) // 是否正在加载更多数据
let totalPage = ref(null) // 总页数
let querys = reactive({
  pageNum: 1,
  pageSize: 10,
  patientQuery: '',
})

const { ctx: that, proxy } = getCurrentInstance()
onLoad(() => {
  _getPatientList(querys)
})

const search = (e) => {
  listArray = []
  querys.patientQuery = e.value ?? ''
  _getPatientList(querys)
}
const clear = (e) => {
  listArray = []
  querys.patientQuery = ''
  _getPatientList(querys)
}
const _getPatientList = async (params) => {
  const res = await getPatientList(params)
  totalPage.value = res?.data?.total
  // 不更新需要splice、forceUpdate 更新视图
  res?.data?.data.length > 0 &&
    res.data.data.forEach((item) => {
      listArray.push(item)
    })
  that.$forceUpdate()
}
// 上拉刷新页面
onPullDownRefresh(() => {
  querys = {
    pageNum: 1,
    pageSize: 10,
    patientQuery: '',
  }
  listArray = []
  _getPatientList(querys)
  setTimeout(function () {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 下拉加载下一页
onReachBottom(() => {
  if (!isLoadingMore.value || param.pageNum >= totalPage.value) {
    return
  }
  param.pageNum++
  isLoadingMore.value = true
  _getPatientList(param)
})
</script>

<template>
  <view class="index">
    <uni-search-bar
      class="uni-mt-10"
      radius="5"
      placeholder="搜索"
      clearButton="auto"
      cancelButton="none"
      @confirm="search"
      @clear="clear"
    />
    <List :listArray="listArray" v-if="listArray.length > 0" />
    <NoData noDataTitle="暂无数据" v-else />
  </view>
</template>

<style lang="scss">
page {
  background-color: #f0f0f0;
}
.uni-searchbar {
  background-color: #fff;
}
.uni-mt-10 .uni-searchbar__box-icon-clear {
  display: flex;
  align-items: center;
  justify-content: center;
}
.uni-mt-10 .uni-icons {
  font-size: 23px !important;
}
</style>
